package com.zjsru.oneDay;

/**
 * 句子中的有效单词数
 * <p>
 * 输入：sentence = "cat and  dog"
 * 输出：3
 * 解释：句子中的有效单词是 "cat"、"and" 和 "dog"
 * <p>
 * 输入：sentence = "alice and  bob are playing stone-game10"
 * 输出：5
 * 解释：句子中的有效单词是 "alice"、"and"、"bob"、"are" 和 "playing"
 * "stone-game10" 不是有效单词，因为它含有数字
 */

 class countValidWords {
    public int countValidWords(String sentence) {
        String[] ss = sentence.split(" ");
        int ans = 0;
        for (String s : ss) {
            if (check(s)) {
                ans++;
            }
        }
        return ans;
    }

    private boolean check(String s) {
        int n = s.length();
        if (n == 0) {
            return false;
        }
        for (int i = 0, c1 = 0, c2 = 0; i < n; i++) {
            char c = s.charAt(i);
            //isDigit() 方法判断指定字符是否为数字
            if (Character.isDigit(c)) return false;
            if (c == ' ') return false;
            if (c == '-' && ++c1 >= 0) {
                if (c1 > 1 || (i == 0 || i == n - 1)) {
                    return false;
                }
                if (!Character.isLetter(s.charAt(i - 1)) || !Character.isLetter(s.charAt(i + 1))) {
                    //	isLetter()检查是否是一个字母
                    return false;
                }
            }
            if ((c == '!' || c == '.' || c == ',') && ++c2 >= 0) {
                if (c2 > 1 || (i != n - 1)) {
                    return false;
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        countValidWords countValidWords = new countValidWords();
        String sentence = "he bought 2 pencils, 3 erasers, and 1  pencil-sharpener.";
        System.out.println(countValidWords.countValidWords(sentence));
    }
}
